package sys_serv

import (
	"strconv"
	"ubt-rbac-service/internal/app/model"
	"ubt-rbac-service/internal/app/model/sys_mod"
	"ubt-rbac-service/internal/app/util"
)

type sysLog struct{}

var SysLogServ = sysLog{}

// Add 新增日志
func (s *sysLog) Add(req *sys_mod.SysLogSaveReq) *model.Result {
	sqlStr := "INSERT INTO sys_log(user_id, mod_code, kind, add_time, opt_org) " +
		"VALUES ($1, $2, $3, EXTRACT(EPOCH FROM NOW()), $4)"
	retCode, retMsg := util.CudData(sqlStr, req.UserId, req.ModCode, req.Kind, req.OptOrg)
	return &model.Result{RetCode: retCode, RetMsg: retMsg}
}

// Count 获取日志数量
func (s *sysLog) Count(req *sys_mod.SysLogPageReq) *model.Result {
	sqlStr := "SELECT COUNT(1) AS nums FROM sys_log WHERE 1=1"
	param := make([]interface{}, 0)
	var n = 0
	if req.UserId != "" {
		n++
		sqlStr += " AND user_id=$" + strconv.Itoa(n)
		param = append(param, req.UserId)
	}
	if req.ModCode != "" {
		n++
		sqlStr += " AND mod_code=$" + strconv.Itoa(n)
		param = append(param, req.ModCode)
	}
	if req.Kind != 0 {
		n++
		sqlStr += " AND kind=$" + strconv.Itoa(n)
		param = append(param, req.Kind)
	}
	if req.BeginDate != 0 {
		n++
		sqlStr += " AND add_time>=$" + strconv.Itoa(n)
		param = append(param, req.BeginDate)
	}
	if req.EndDate != 0 {
		n++
		sqlStr += " AND add_time<=$" + strconv.Itoa(n)
		param = append(param, req.EndDate)
	}
	if dbMap, err := util.GetOne(sqlStr, param...); err == nil && len(dbMap) > 0 {
		return &model.Result{RetCode: 1001, RetMsg: "ok", RetData: dbMap["nums"]}
	} else {
		return &model.Result{RetCode: 1000, RetMsg: "暂无内容"}
	}
}

// Page 获取日志分页列表
func (s *sysLog) Page(req *sys_mod.SysLogPageReq) *model.Result {
	sqlStr := "SELECT a.log_id, b.nick_name||'('||b.usname||')' log_user, c.mod_name||'['||c.mod_code||']' mod_name, a.kind, a.add_time " +
		"FROM sys_log a LEFT JOIN sys_user b ON a.user_id=b.user_id LEFT JOIN sys_module c ON a.mod_code=c.mod_code WHERE 1=1"
	param := make([]interface{}, 0)
	var n = 0
	if req.UserId != "" {
		n++
		sqlStr += " AND a.user_id=$" + strconv.Itoa(n)
		param = append(param, req.UserId)
	}
	if req.ModCode != "" {
		n++
		sqlStr += " AND a.mod_code=$" + strconv.Itoa(n)
		param = append(param, req.ModCode)
	}
	if req.Kind != 0 {
		n++
		sqlStr += " AND a.kind=$" + strconv.Itoa(n)
		param = append(param, req.Kind)
	}
	if req.BeginDate != 0 {
		n++
		sqlStr += " AND a.add_time>=$" + strconv.Itoa(n)
		param = append(param, req.BeginDate)
	}
	if req.EndDate != 0 {
		n++
		sqlStr += " AND a.add_time<=$" + strconv.Itoa(n)
		param = append(param, req.EndDate)
	}
	sqlStr += " ORDER BY a.add_time DESC LIMIT $" + strconv.Itoa(n+1) + " OFFSET $" + strconv.Itoa(n+2)
	param = append(param, req.Limit)
	param = append(param, req.Offset)
	if dbMap, err := util.GetAll(sqlStr, param...); err == nil && len(dbMap) > 0 {
		return &model.Result{RetCode: 1001, RetMsg: "ok", RetData: dbMap}
	} else {
		return &model.Result{RetCode: 1000, RetMsg: "暂无内容"}
	}
}
